import React, { useEffect, useTransition,useState  } from 'react'
import {Button, Card,Modal,Form,type FormProps, Input,message,Select  } from 'antd'
import { ExclamationCircleOutlined  } from '@ant-design/icons'; 
import { useNavigate } from 'react-router-dom';
import { ProFormColumnsType } from '@ant-design/pro-components'
import {  changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser } from '@/api/system/user'
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import md5 from "js-md5"

const { Option } = Select; 
type FieldType = {
    username?: string;
    password?: string;
    phonenumber?:string;
    userId?:number;
    roleId?:number;
  };

const User = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [modalVisible, setModalVisible] = useState(false);  
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [userTitle,setUserTitle] = useState("")
  const [roleList, setRoleList] = useState([]); // 存储角色列表的状态  
  const [selectedRoleId, setSelectedRoleId] = useState(null); // 存储选中角色的id
  const [form] = Form.useForm();  
  const [onReloadNum,setOnReloadNum] = useState(null)
  const [visData,setVisData] = useState(true)

  const formColumns:ProFormColumnsType[] = [{
    title: '用户名称',
    dataIndex: 'userName',
    valueType: 'text', 
  },{
    title: '手机号码',
    dataIndex: 'phonenumber',
    valueType: 'text', 
  },]


  const columns: any = [
    {
      title: '用户编号',
      dataIndex: 'userId',
      key: 'userId',
      width:80,
      fixed:'left',
    },
    {
      title:'用户名称',
      dataIndex: 'userName',
      key: 'userName',
      width:100,
      fixed:'left',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      key: 'nickName',
      width:160,
      fixed:'left',
    },
    {
      title: '部门',
      dataIndex: 'dept.deptName',
      key: 'dept.deptName',
      width:80,
      fixed:'left',
    },
    {
      title: '手机号码',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
      width:100,
      fixed:'left',
    },
    {
        title: t('action'),
        width: 120,
        fixed: 'right',
        render: (_, record) => {
            const handleEdit = () => {  
                //进行弹窗
                setUserTitle('修改用户')
                const userId = record.userId
                getUser(userId).then(response => {
                    let data1 = response.data.data
                    data1.roleIds = response.data.roleIds
                    form.setFieldsValue(data1); // 设置表单字段的值 
                    setRoleList(response.data.roles)
                    setSelectedRecord(record);  
                    setModalVisible(true);  
                    let abc = form.getFieldsValue()
                    console.log(abc,'form')
                  });
       
              }; 
              const handleRecover = () =>{
                changeUserStatus(record.userId,'0').then(response=>{
                  message.success("Success")
                  setOnReloadNum(Date.now())
                }) 
              }
              const showDeleteConfirm = () => {  
                Modal.confirm({  
                  title: 'Confirm Delete User?',  
                  icon: <ExclamationCircleOutlined />,  
                  okText: '确认/Ok',  
                  cancelText: '取消/Cancel',  
                  onOk() {  
                    console.log(record,'record')
                     changeUserStatus(record.userId,'1').then(response=>{
                      message.success("Success")
                      setOnReloadNum(Date.now())
                    }) 
                  },  
                  onCancel() {  
                    console.log('Cancel');  
                  },  
                });  
              };  
            if(record.userName == 'admin'){
              //
            }else{
              return (<>
                <Button type='link' onClick={handleEdit}>{t('edit')}</Button>
                {/* 使用三元运算符来判断显示哪个按钮 */}  
                {record.status === '1' ? (  
                  <Button type='link' danger onClick={handleRecover}>{t('recover')} </Button>
                ) : (  
                  <Button type='link' danger onClick={showDeleteConfirm}>{t('delete')} </Button>
                )}
                {/* <Button type='link' onClick={showDeleteConfirm}>删除</Button> */}
              </>)
            }
          
        }
      }
  ];

  const handleDelete = (userId) => {
    const id = userId
    console.log(userId,'record')
    delUser(id).then(res=>{
        if(res.data.code ==200){
            // 假设你已经处理完数据，关闭弹窗  
            message.success('用户删除成功'); 
            setOnReloadNum(Date.now())
        }else{
            message.error('用户删除失败：' + res.data.msg); 
        }
    })
}

  const handleAdd = () =>{
    form.resetFields()
    setSelectedRecord(null)
    getUser().then(res=>{
        setRoleList(res.data.roles)
        console.log(res.data.roles,'getUser')
        setUserTitle('新增用户')
        setModalVisible(true); 
    })

  }

  const showAllData = () =>{
    setVisData(false)
    setOnReloadNum(Date.now())
  }

  const showNoAllData = () =>{
    setVisData(true)
    setOnReloadNum(Date.now())
  }

  const renderOperator = <>
    <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
    <Button style={{marginLeft:'1%'}} type="primary"  size="small" onClick={showAllData}>{t('allData')}</Button>
    <Button style={{marginLeft:'1%'}} type="primary"  size="small" onClick={showNoAllData}>{t('nonInvisibleData')}</Button>
  </>


  const getData = async (formData) => {
    if(visData==false){
      const { success, data} = await listUser({...formData,status:'' })
      if(!success) return false
      console.log(data)
      const list = data.rows
      return {
        data: list,
        total: data.total
      }
    }else{
      const { success, data} = await listUser({...formData,status:'0' })
      if(!success) return false
      console.log(data)
      const list = data.rows
      return {
        data: list,
        total: data.total
      }
    }
  
  } 

  const handleModalCancel = () => {  
    form.resetFields(); // 重置表单字段  
    setModalVisible(false);  
  };   

   // 处理选中角色变化  
   const handleRoleChange = (value) => {  
    setSelectedRoleId(value); // 保存选中角色的id  
  };  


  const handleFormFinish = (values) => {  
    // 处理表单提交逻辑，比如发送API请求  
    console.log('Form values:', values);
    if(userTitle=='新增用户'){
        values.userId = null
        values.password = md5(values.password)
        addUser(values).then(res=>{
            console.log(res,'res')
            if(res.data.code ==200){
                // 假设你已经处理完数据，关闭弹窗  
                message.success('用户添加成功');
                handleModalCancel();  
                setOnReloadNum(Date.now())
            }else{
                message.error('用户添加失败：' + res.data.msg); 
            }
        })  
    }else{
        // values.password = md5(values.password)
        updateUser(values).then(res=>{
            console.log(res,'res')
            if(res.data.code ==200){
                // 假设你已经处理完数据，关闭弹窗  
                message.success('用户更新成功');
                handleModalCancel();  
                 setOnReloadNum(Date.now())
            }else{
                message.error('用户更新失败：' + res.data.msg); 
            }
        })  
    }
  
  };  
  // 根据 userTitle 的值来决定是否显示密码输入框  
  const isPasswordVisible = userTitle === '新增用户';  
  return (
    <>
    <MemoTable 
      name='user'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='userId'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
     <Modal  
        title={userTitle}  
        visible={modalVisible}  
        onCancel={handleModalCancel}  
        footer={[  
          <Button key="back" onClick={handleModalCancel}>  
            取消  
          </Button>,  
          <Button key="submit" type="primary" onClick={() => form.validateFields().then(handleFormFinish)}>  
            提交  
          </Button>,  
        ]}  
      >  
        <Form form={form} layout="vertical" onFinish={handleFormFinish}>  
          {/* 假设userId是只读的，不需要编辑 */}  
          <Form.Item  
            name="userId"  
            label="用户ID"  
            hidden
            initialValue={selectedRecord?.userId} // 初始化值  
          >  
            <Input disabled />  
          </Form.Item> 
          <Form.Item  
            name="userName"  
            label="用户名"  
            rules={[{ required: true, message: '请输入用户名!' }]}  
          >  
            <Input />  
          </Form.Item>  
  
          <Form.Item  
            name="nickName"  
            label="用户昵称"  
            rules={[{ required: true, message: '请输入昵称!' }]}  
          >  
            <Input />  
          </Form.Item>  
  
          <Form.Item  
            name="phonenumber"  
            label="电话号码"  
            // rules={[{ required: true, message: '请输入电话号码!', pattern: /^\d{11}$/, message: '请输入11位手机号码!' }]}  
          >  
            <Input />  
          </Form.Item>
          {isPasswordVisible && (
                    <Form.Item  
                    name="password"  
                    label="密码"  
                    rules={[{ required: true, message: '请输入密码!' }]}  
                  >  
                    <Input />  
                  </Form.Item>  
          )}  
  
          <Form.Item  
            name="roleIds"  
            label="角色"  
            // rules={[{ required: true, message: '请输入密码!' }]}  
          >  
            <Select  
                showSearch  
                mode="multiple" // 设置为多选模式 
                placeholder="请选择角色"  
                value={selectedRoleId} // 绑定选中角色的id  
                onChange={handleRoleChange} // 处理选中变化  
                filterOption={false} // 如果使用搜索功能，设置为false避免根据输入内容过滤选项  
            >  
                {roleList.map((role) => (  
                <Option key={role.roleId} value={role.roleId}>
                    {role.roleName} 
                </Option>  
                ))}  
            </Select>   
          </Form.Item>  
        </Form>  
      </Modal>   
    </>
  )
}
export default User
